<template>
  <div class="app-container">
    <!-- 上半部分：搜索和销售出库表格 -->
    <div class="top-section">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="queryParams" class="search-form" size="small">
        <el-form-item label="出库单号">
          <el-input v-model="queryParams.sales_code" placeholder="请输入出库单号" clearable />
        </el-form-item>
        <el-form-item label="出库单名称">
          <el-input v-model="queryParams.sales_name" placeholder="请输入出库单名称" clearable />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="queryParams.customer_name" placeholder="请输入客户名称" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
            <el-option label="待提交" value="1" />
            <el-option label="待质检" value="2" />
            <el-option label="合格" value="3" />
            <el-option label="不合格" value="4" />
            <el-option label="部分合格" value="5" />
            <el-option label="已出库" value="6" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="operation-buttons">
        <div class="left-buttons">
          <el-button type="primary" plain @click="handleAdd">
            <i class="el-icon-plus"></i> 新增
          </el-button>
          <el-button type="danger" plain :disabled="!deletableRows.length" @click="handleBatchDelete">
            <i class="el-icon-delete"></i> 批量删除
          </el-button>
        </div>
        <div class="top-right-btn">
          <el-button icon="el-icon-search" circle />
          <el-button icon="el-icon-refresh" circle @click="getList" />
        </div>
      </div>

      <!-- 销售出库表格 -->
      <el-table
        v-loading="loading"
        :data="salesList"
        @selection-change="handleSelectionChange"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="sales_code" label="出库单号" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" @click="handleViewDetail(scope.row)">
              {{ scope.row.sales_code }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="sales_name" label="出库单名称" align="center" show-overflow-tooltip />
        <el-table-column prop="customer_name" label="客户名称" align="center" show-overflow-tooltip />
        <el-table-column prop="recipient" label="收货人" align="center" show-overflow-tooltip />
        <el-table-column prop="sales_date" label="出库日期" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.sales_date">{{ formatDateTime(scope.row.sales_date) }}</span>
            <span v-else>待出库</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="收货地址" align="center" width="180" show-overflow-tooltip />
        <el-table-column prop="carrier" label="承运商" align="center" show-overflow-tooltip />
        <el-table-column prop="status" label="订单状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" align="center">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="{ row }">
            <template v-if="row.status === '1'">
              <el-button type="text" @click="handleEdit(row)">
                <i class="el-icon-edit"></i> 修改
              </el-button>
              <el-button type="text" @click="handleDelete(row)">
                <i class="el-icon-delete"></i> 删除
              </el-button>
              <el-button type="text" @click="handleSubmit(row)">
                <i class="el-icon-check"></i> 提交
              </el-button>
            </template>
            <template v-else-if="row.status === '2'">
              <span>---</span>
            </template>
            <template v-else-if="row.status === '3'">
              <el-button type="text" @click="handleWarehouse(row)">
                <i class="el-icon-shopping-cart-2"></i> 出库
              </el-button>
            </template>
            <template v-else-if="row.status === '6'">
              <el-button type="text" @click="handleDelete(row)">
                <i class="el-icon-delete"></i> 删除
              </el-button>
            </template>
            <template v-else>
              <span>---</span>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 销售出库分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    
    <!-- 出库单详情对话框 -->
    <el-dialog :title="`出库单详情 - ${currentOutbound.sales_code || ''}`" :visible.sync="detailDialogVisible" width="1200px" append-to-body>
      <div v-if="currentOutbound.sales_id" class="outbound-info">
        <div class="info-section">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="出库单名称">{{ currentOutbound.sales_name }}</el-descriptions-item>
            <el-descriptions-item label="客户名称">{{ currentOutbound.customer_name }}</el-descriptions-item>
            <el-descriptions-item label="收货人">{{ currentOutbound.recipient }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentOutbound.tel }}</el-descriptions-item>
            <el-descriptions-item label="收货地址">{{ currentOutbound.address }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(currentOutbound.status)">
                {{ getStatusText(currentOutbound.status) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="table-section" style="margin-top: 20px;">
          <div class="section-title">出库产品明细</div>
          <el-table
            :data="outboundItems"
            style="width: 100%"
            border
            v-loading="detailLoading"
          >
            <el-table-column prop="product_code" label="产品编号" align="center" width="150" />
            <el-table-column prop="product_name" label="产品名称" align="center" show-overflow-tooltip />
            <el-table-column prop="stock_sfn" label="规格型号" align="center" width="150" show-overflow-tooltip />
            <el-table-column prop="unit" label="单位" align="center" width="80" />
            <el-table-column prop="sales_num" label="出库数量" align="center" width="100">
              <template slot-scope="scope">
                {{ formatNumber(scope.row.sales_num) }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
            <el-table-column label="操作" align="center" width="120">
              <template slot-scope="scope">
                <template v-if="currentOutbound.status !== '1' && currentOutbound.status !== '2'">
                   <el-button type="text" @click="handleViewQcReport(scope.row)">查看质检单</el-button>
                </template>
                <template v-else>
                  ---
                </template>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 商品明细分页 -->
          <pagination
            v-show="goodsQuery.total > 0"
            :total="goodsQuery.total"
            :page.sync="goodsQuery.pageNum"
            :limit.sync="goodsQuery.pageSize"
            @pagination="handleGoodsPagination"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入API
import { listOutbound, deleteOutbound, deleteOutboundBatch, submitOutbound, warehouseOutbound, updateOutboundStatus, getOutbound, getOutboundItems } from "@/views/ck/js/outbound"
import Pagination from "@/components/Pagination"

export default {
  name: 'MaterialOutbound',
  components: {
    Pagination
  },
  data() {
    return {
      loading: false,
      selectedRows: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sales_code: undefined,
        sales_name: undefined,
        customer_name: undefined,
        status: undefined
      },
      salesList: [],
      total: 0,
      // 详情对话框数据
      detailDialogVisible: false,
      currentOutbound: {},
      outboundItems: [],
      detailLoading: false,
      goodsQuery: {
        sales_id: '',
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
    }
  },
  computed: {
    // 计算属性：获取可删除的出库单（待提交或已出库状态）
    deletableRows() {
      return this.selectedRows.filter(row => ['1', '6'].includes(row.status));
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      // 使用真实API获取数据
      listOutbound(this.queryParams).then(response => {
        this.salesList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error('获取销售出库单列表失败:', error);
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        sales_code: undefined,
        sales_name: undefined,
        customer_name: undefined,
        status: undefined
      }
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    handleAdd() {
      this.$router.push('/ck/SalesOutbound/add')
    },
    handleEdit(row) {
      this.$router.push({
        path: '/ck/SalesOutbound/update',
        query: { order: JSON.stringify(row) }
      })
    },
    
    handleDelete(row) {
      this.$confirm(`确认删除销售出库单"${row.sales_name}"吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 使用真实API删除数据
        const update_by = this.$store.getters.name;
        deleteOutbound(row.sales_id, update_by).then(() => {
          this.$message.success('删除成功');
          this.getList();
        }).catch(error => {
          console.error('删除销售出库单失败:', error);
          this.$message.error('删除失败');
        });
      }).catch(() => {})
    },

    // 批量删除方法
    handleBatchDelete() {
      const deletableRows = this.deletableRows;
      if (deletableRows.length === 0) {
        this.$message.warning('请选择状态为"待提交"或"已出库"的出库单进行删除');
        return;
      }
      
      const totalSelected = this.selectedRows.length;
      const deletableCount = deletableRows.length;
      
      const salesNames = deletableRows.map(row => row.sales_name);
      const displayNames = salesNames.length > 3
        ? salesNames.slice(0, 3).join('、') + `等${deletableRows.length}个出库单`
        : salesNames.join('、');
        
      let confirmMessage = `确认删除以下出库单吗？<br/><br/>${displayNames}`;
      
      if (totalSelected > deletableCount) {
        confirmMessage += `<br/><br/><span style="color: #E6A23C;">注意：您选择了${totalSelected}个出库单，但只有${deletableCount}个（状态为“待提交”或“已出库”）将被删除。</span>`;
      }

      this.$confirm(confirmMessage, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const ids = deletableRows.map(row => row.sales_id);
        const update_by = this.$store.getters.name;
        this.loading = true;
        deleteOutboundBatch(ids, update_by).then(() => {
          this.loading = false;
          this.$message.success('删除成功');
          this.getList();
        }).catch(error => {
          this.loading = false;
          console.error('批量删除出库单失败:', error);
          this.$message.error('删除失败');
        });
      }).catch(() => {});
    },

    // 提交出库单
    handleSubmit(row) {
      this.$confirm(`确认提交销售出库单"${row.sales_name}"吗？提交后将变为待质检状态，且无法修改或删除`, '提交确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在提交出库单，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        // 使用新的API函数更新状态为2（待质检）
        updateOutboundStatus(row.sales_id, '2').then(response => {
          loading.close();
          if (response.code === 200) {
            this.$message.success('销售出库单提交成功');
            this.getList(); // 刷新列表
          } else {
            this.$message.error(response.msg || '提交失败');
          }
        }).catch(error => {
          console.error('提交销售出库单失败:', error);
          loading.close();
          this.$message.error('提交失败');
        });
      }).catch(() => {});
    },
    
    // 出库单
    handleWarehouse(row) {
      this.$confirm(`确认将销售出库单"${row.sales_name}"出库吗？出库后状态将变更为已出库`, '出库确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '正在处理出库操作，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
  
        // 获取当前用户
        const update_by = this.$store.getters.name;
        
        // 使用真实API进行出库操作
        warehouseOutbound(row.sales_id,update_by).then(() => {
          loading.close();
          this.$message.success('销售出库单出库成功');
          this.getList(); // 刷新列表
        }).catch(error => {
          loading.close();
          console.error('销售出库单出库操作失败:', error);
          this.$message.error('出库操作失败');
        });
      }).catch(() => {});
    },

    // 查看详情
    handleViewDetail(row) {
      this.currentOutbound = row;
      this.detailLoading = true;
      
      // 设置查询参数
      this.goodsQuery.sales_id = row.sales_id;
      this.goodsQuery.pageNum = 1;
      
      // 获取出库商品明细（分页）
      this.getOutboundItems();
      
      // 显示对话框
      this.detailDialogVisible = true;
    },

    // 获取出库单商品明细（分页）
    getOutboundItems() {
      this.detailLoading = true;
      getOutboundItems(this.goodsQuery).then(response => {
        this.outboundItems = response.rows || [];
        console.log("测试获取到的条数：",response.total)
        this.goodsQuery.total = response.total || 0;
        this.detailLoading = false;
      }).catch(error => {
        console.error('获取出库单商品明细失败:', error);
        this.detailLoading = false;
        this.$message.error('获取出库单商品明细失败');
      });
    },

    // 商品分页切换
    handleGoodsPagination() {
      this.getOutboundItems();
    },
    
    formatDateTime(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, '0');
      const day = d.getDate().toString().padStart(2, '0');
      const hours = d.getHours().toString().padStart(2, '0');
      const minutes = d.getMinutes().toString().padStart(2, '0');
      const seconds = d.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    getStatusType(status) {
      const statusMap = {
        '1': 'info',    // 待提交
        '2': 'warning', // 待质检
        '3': 'success', // 合格
        '4': 'danger',  // 不合格
        '5': 'warning', // 部分合格
        '6': 'primary'  // 已出库
      }
      return statusMap[status] || 'info'
    },
    
    getStatusText(status) {
      const statusMap = {
        '1': '待提交',
        '2': '待质检',
        '3': '合格',
        '4': '不合格',
        '5': '部分合格',
        '6': '已出库'
      }
      return statusMap[status] || '未知'
    },

    formatNumber(value) {
      if (value === null || value === undefined) {
        return '0';
      }
      return Number(value).toFixed(2);
    },

    // 查看质检单
    handleViewQcReport(row) {
      // 假设row对象中有oqc_id，用于跳转
      console.log("测试查看质检单：",row)
      this.$router.push({
        path: `/qc/OutgoingInspection/detail/${row.oqc_id}`
      });
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.top-section {
  margin-bottom: 30px;
  width: 100%;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
}

.operation-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.left-buttons {
  display: flex;
  gap: 5px;
}

.top-right-btn {
  display: flex;
  gap: 10px;
}

.el-table {
  margin-bottom: 20px;
  width: 100% !important;
}

.el-table th {
  background-color: #f5f7fa;
}

/* 确保表格容器也是100%宽度 */
.el-table__body-wrapper {
  width: 100%;
}

.el-table__header-wrapper {
  width: 100%;
}

/* 操作列紧贴右边界 */
.el-table .el-table__cell:last-child {
  padding-right: 0 !important;
}

.el-table .el-table__cell:last-child .cell {
  padding-right: 10px !important;
}
</style>
